#include<stdio.h>
#include<stdlib.h>
#include"fm_list.h"
#include"fm_func.h"
#include"fm_window.h"
#include"fm_core.h"
#include"fm_records.h"
#include<gui_window.h>
#include<gui_box.h>
#include<gui_button.h>
#include<gui_label.h>

gui_spirit_t *fm_cwd_label; //used to update label text


static void fm_func_change_dir(char *path)
{
     fm_list_clear();
     fm_dir_open(path);
     fm_label_update(path);
     if(chdir(path)<0)
        return 0;
}

void fm_label_update(char *text)
{
    gui_label_set_text(fm_cwd_label,text,min(MAX_PATH_LEN,strlen(text)+1));
    gui_spirit_show(fm_cwd_label);
}

static int fm_func_up_btn_handle(gui_spirit_t *spirit)
{
    dprintf("[fm func] up btn press\n");
    char path[MAX_PATH_LEN]={0};
    if(!fm_records_back(path,MAX_PATH_LEN))
    {
        dprintf("[fm] back: open %s\n",path);
        fm_func_change_dir(path);
        return 0;
    }
    //open root 
    fm_func_change_dir("/");
    return 0;
}

static int fm_func_down_btn_handle(gui_spirit_t *spirit)
{
    dprintf("[fm func] down btn press");
    char path[MAX_PATH_LEN]={0};
    if(!fm_records_forward(path,MAX_PATH_LEN))
    {
        dprintf("[fm] forward: open %s\n",path);
        fm_func_change_dir(path);
        return 0;
    }
    return 0;
}

gui_spirit_t *fm_func_create(int width,int height)
{
    gui_spirit_t *box=gui_box_create(GUI_BOX_ORIENTATION_HORIZONTAL,fm_surface->w,20,0);
    if(!box)
    {
        dprintf("[gui] box create failed\n");
        return NULL;
    }
    //create widget 
    fm_func_init(box);
    
    //gui_spirit_set_pos(box,0,fm_list->height);
    gui_container_add(GUI_CONTAINER(fm_window),box);
    gui_spirit_show_all(box);
    return box;
}

int fm_func_init(gui_spirit_t *box)
{
    gui_button_t *up_button;
    gui_button_t *down_button;
    gui_label_t *cwd_label;

    up_button=gui_button_create_with_label("up");
    if(!up_button)
    {
        dprintf("[fm] create up button error\n");
    }
    down_button=gui_button_create_with_label("down");
    if(!down_button)
    {
        dprintf("[fm] create down button error\n");
    }
    cwd_label=gui_label_create("/");
    if(!cwd_label)
    {
        dprintf("[fm] create cwd label error\n");
    }
    fm_cwd_label=cwd_label; //record cwd label 

    gui_spirit_reset_size(up_button,FM_FUNC_BUTTON_SIZE_W,FM_FUNC_BUTTON_SIZE_H);
    gui_spirit_reset_size(down_button,FM_FUNC_BUTTON_SIZE_W,FM_FUNC_BUTTON_SIZE_H);

    int x=1,y=1;
    gui_spirit_set_pos(up_button,x,y);
    x+=FM_FUNC_BUTTON_SIZE_W+2;
    gui_spirit_set_pos(down_button,x,y);
    x+=FM_FUNC_BUTTON_SIZE_W+2;
    gui_spirit_set_pos(cwd_label,x,y);


    //connect signal event function
    gui_signal_connect(up_button,"button_press",fm_func_up_btn_handle,NULL);
    gui_signal_connect(down_button,"button_press",fm_func_down_btn_handle,NULL);

    gui_container_add(GUI_CONTAINER(box),up_button);
    gui_container_add(GUI_CONTAINER(box),down_button);
    gui_container_add(GUI_CONTAINER(box),cwd_label);
}
